package com.example.enjoyarkuix;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.example.enjoyarkuix.R;
import com.example.enjoyarkuix.base.BaseActivity;
import com.example.enjoyarkuix.bean.ItemDataBean;
import com.example.enjoyarkuix.common.Constant;
import com.example.enjoyarkuix.util.DownloadUtil;
import com.example.enjoyarkuix.util.UnzipUtil;
import com.example.enjoyarkuix.util.Util;

import java.io.File;

/*
 * https://gitee.com/arkui-x/docs/blob/master/zh-cn/application-dev/tutorial/how-to-use-dynamic-on-android.md
 *
 * */
public class DynamizationJumpActivity extends BaseActivity {

    private static String TAG = "DynamizationActivity";
    private static final int UNZIP_FROM_ASSERT = 0;
    private static final int UNZIP_FROM_CLOUD = 1;
    //动态化加载需要复制的文件名
    String DynamizationFileName = "/zipContent";
    String DynamizationZipFileName = DynamizationFileName + ".zip";
    //动态化加载需要复制的文件所在的assert中文件夹
    String assertPath = "arkui-x/test";
    //是否正在下载
    private boolean isDownloading = false;

    //需要复制到沙箱中的路径
    private String mTargetPath;
    private static Context mContext;
    private Button mButtonDown;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dynamization);
        initTopBar("动态化");
        mContext = this;
        mTargetPath = getFilesDir().getPath() + "/arkui-x";

        //从云端下载文件
        mButtonDown = (Button) findViewById(R.id.buttonDown);
        mButtonDown.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                downFileFromCloud();
            }
        });


        Button buttonCopy = (Button) findViewById(R.id.buttonCopy);
        buttonCopy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                copyFolderFromAssets();
            }
        });

        //打开动态化页面
        Button buttonOpen = (Button) findViewById(R.id.buttonOpen);
        buttonOpen.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                openDynamizationPage();
            }
        });

        //删除沙箱下文件
        Button buttonDelete = (Button) findViewById(R.id.buttonDelete);
        buttonDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                File file1 = new File(mTargetPath + "/fang_application");
                deleteDirWihtFile(file1);
                File file2 = new File(mTargetPath + "/opencvmodule");
                deleteDirWihtFile(file2);
                File file3 = new File(mTargetPath + "/__MACOSX");
                deleteDirWihtFile(file3);
                File file4 = new File(mTargetPath + "/zipContent.zip");
                deleteDirWihtFile(file4);
            }
        });
    }

    private static void openDynamizationPage() {
        //                ItemDataBean itemDataBean = new ItemDataBean("动态化", Constant.JUDPT_ENTRY_ENTRY_ABILITY_ACTIVITY, "dynamization", "DynamizationAbility");
        ItemDataBean itemDataBean = new ItemDataBean("动态化", Constant.JUDPT_ENTRY_ENTRY_ABILITY_ACTIVITY, "fang_application", "Fang_applicationAbility");
        Intent intent = new Intent();
        Bundle bundle = new Bundle();
        bundle.putSerializable("ItemDataBean", itemDataBean);//序列化
        intent.putExtras(bundle);//发送数据
        intent.setClass(mContext, EntryCommonAbilityActivity.class);
        mContext.startActivity(intent);
    }


    /**
     * 从云端下载
     */
    private void downFileFromCloud() {
        if (isDownloading)
        {
            return;
        }
        String url = "https://note.youdao.com/yws/public/resource/7bcafc7245d02429559bf4092aa2f9c4/xmlnote/WEBRESOURCE805d29bc1f1f1d54a37352496300f1d9/3";
        String downFileName = "zipContent.zip";
        String savePath = getFilesDir().getPath() + "/arkui-x";
        DownloadUtil.get().download(url, savePath, downFileName, new DownloadUtil.OnDownloadListener() {
            @Override
            public void onDownloadSuccess() {
                Log.i(TAG, "============下载完成");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(DynamizationJumpActivity.this, "下载完成", Toast.LENGTH_SHORT).show();
                        //待处理压缩文件路径
                        String zipPath = mTargetPath + "/" + downFileName;
                        //解压后要保存的目录
                        String outPath = mTargetPath;
                        //解压缩
                        unzip(zipPath, outPath, UNZIP_FROM_CLOUD);
                    }
                });
            }

            @Override
            public void onDownloading(int progress) {
                isDownloading = true;
                mButtonDown.setText("下载进度: " + progress + "%");
//                     Log.i("dyp","============"+progress);
            }

            @Override
            public void onDownloadFailed() {
                Log.i(TAG, "============下载失败");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        isDownloading = false;
                        mButtonDown.setText(getResources().getString(R.string.from_cloud_down));
                        Toast.makeText(DynamizationJumpActivity.this, "下载失败", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
    }


    /**
     * 删除文件夹和文件夹里面的文件
     *
     * @param dir
     */
    public static void deleteDirWihtFile(File dir) {
        if (dir == null || !dir.exists() || (!dir.isDirectory()&&!dir.isFile()))
            return;
        if (dir.isFile())
        {
            dir.delete();
        }else {
            for (File file : dir.listFiles()) {
                if (file.isFile())
                    file.delete(); // 删除所有文件
                else if (file.isDirectory())
                    deleteDirWihtFile(file); // 递规的方式删除文件夹
            }
            dir.delete();// 删除目录本身
        }
    }

    /**
     * 从assets拷贝文件到沙箱下
     */
    private void copyFolderFromAssets() {
        //从assert/test中复制到沙箱中/data/data/com.example.enjoyarkuix/files/arkui-x
        Util.copyFolderFromAssets(mContext, assertPath, mTargetPath);
        //待处理压缩文件路径
        String zipPath = mTargetPath + DynamizationZipFileName;
        //解压后要保存的目录
        String outPath = mTargetPath;
        unzip(zipPath, outPath, UNZIP_FROM_ASSERT);
    }

    /**
     * 解压缩
     *
     * @param zipPath     待解压文件
     * @param outPath     解压路径
     * @param unzipTagOne
     */
    private void unzip(String zipPath, String outPath, int unzipTagOne) {
        Log.d(TAG, "正在解压...");
        UnzipUtil.decompressFile(outPath,zipPath,new UnzipUtil.ZipResultCall() {
            @Override
            public void zipSuccessfUL(boolean isSuccessfUL) {
                if (isSuccessfUL) {
                    Toast.makeText(mContext, "解压成功", Toast.LENGTH_SHORT).show();
                    Log.d(TAG, "解压成功...");
                    isDownloading = false;
                    //直接打开动态化页面
                    openDynamizationPage();
                } else {
                    Toast.makeText(mContext, "解压失败", Toast.LENGTH_SHORT).show();
                    Log.d(TAG, "解压失败...");
                }
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mButtonDown.getText().equals("下载进度: 100%"))
        {
            mButtonDown.setText(getResources().getString(R.string.from_cloud_down));
        }
    }
}